package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user/passport")
public class UserApiController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    //用户登录
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo){

        //通过查询数据库判断用户是否登录成功
        UserInfo user = userService.login(userInfo);
        //判断用户是否登录成功
        if (user != null){
            Map map = new HashMap();
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            map.put("token",uuid);
            map.put("nickName",user.getNickName());
            //map.put("name",user.getName());
            redisTemplate.opsForValue().set(uuid,user.getId().toString(),
                    RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            return Result.ok(map);
        } else {
            return Result.fail().message(ResultCodeEnum.FAIL.getMessage());
        }

    }

    //用户退出
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request){
        //退出清空redis缓存
        String token = request.getHeader("token");
        redisTemplate.delete(token);
        //System.out.println(token);
        return Result.ok();
    }

    //查询地址集合
    @GetMapping("/selectAddress")
    public Result selectAddress(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        List<UserAddress> userAddressList = userService.selectAddress(userId);
        return Result.ok(userAddressList);
    }
}
